//
//  ComSearch2V.swift
//  ANOA
//
//  Created by 邱仙凯 on 2023/2/11.
//  Copyright © 2023 zwb. All rights reserved.
//   左边搜索框 右边日期的固定搜索

import UIKit

let comBannarItemH = 32

class ComSearch2V:UIView,UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout  {
    var filterV:KSBaseFilterV?
    var fiBannerShowData:[BannerData] = []
  
    
    var bannerComfirmClo:(()->())?
    
    
    lazy var bg:UIView = {
        let v = UIView()
        v.layer.cornerRadius = 5
        //        v.backgroundColor = UIColor(kshex: "#E5E8EE")
        return v
    }()
    
    lazy var saiBtn:FFButton = {
        let v = FFButton()
        v.setTitle("筛选", for: .normal)
        v.setImage(UIImage(named: "filter_ld"), for: .normal)
        v.setTitleColor(.black, for: .normal)
        v.titleLabel?.font = UIFont.systemFont(ofSize: 15)
        return v
    }()
    
    lazy var collectionView:UICollectionView = {
        // 1.创建layout
        let layout = UICollectionViewFlowLayout()
        layout.itemSize = CGSize(width: CollecWidth - 0.5, height: CGFloat(comBannarItemH))
        layout.minimumLineSpacing = 0
        layout.minimumInteritemSpacing = 8
        layout.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
        layout.scrollDirection = .horizontal
        // 2.创建UICollectionView
        let v = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout)
        v.backgroundColor = .white
        v.showsHorizontalScrollIndicator = false
        v.register(ComSearColleCell.self, forCellWithReuseIdentifier: ComSearColleCell.identifier)
        
        return v
    }()
    var dataArray = [BannerData]()
    var maxlengths = [Int]()
   
    
    
    

    func setBannerData(arr:[BannerData]) {
        self.dataArray = arr
        var widths = [Int]()
        let nmArr = arr.compactMap{$0.content}
        for itemx in  nmArr {
            var size = itemx.sizeWithFont(font: UIFont.systemFont(ofSize: 14), maxSize:CGSizeMake(180, 30))
            var w = size.width
//            var w = 33 + itemx.count * 12
// 宽度 上限  下限
            if w < 100 {
                w = 100
            } else if w > 165 {
                w = 165
            }
             widths.append(Int(w))
            
        }
        maxlengths = widths
        
        
        self.collectionView.reloadData()
    }
    
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return self.dataArray.count
        
    }
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        
        
        let ww = indexPath.row
        return CGSize(width: maxlengths[ww], height: comBannarItemH)
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ComSearColleCell.identifier, for: indexPath as IndexPath) as! ComSearColleCell
        let one = self.dataArray[indexPath.row]
        if one.content.unwrap != "" {
            cell.title.setTitle(one.content, for: .normal)
            cell.setHasContent(true)
        } else {
            cell.title.setTitle(one.title, for: .normal)
            cell.setHasContent(false)
        }
        
        
        
        
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        self.collectionView.reloadData()
        
        for i in 0..<self.filterV!.fContentArr.count {
            if i == indexPath.row {
                self.filterV!.fContentArr[i].isUserShow = true
            } else {
                self.filterV!.fContentArr[i].isUserShow = false

            }
        }
        self.bannerSHowFilter()
        
        
        
    }
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        
        self.backgroundColor = .white
        
        self.addSubview(bg)
        
        bg.snp.makeConstraints { make in
            make.edges.equalTo(UIEdgeInsets(top: 3, left: 3, bottom: 3, right: 3))
        }
        bg.addSubview(saiBtn)
        saiBtn.addTouchUpInSideAction { _ in
            
            self.saiBtn.setTitleColor(UIColor(kshex: "#4972F9"), for: .normal)
            if self.filterV.isSome {
                for i in 0..<self.filterV!.fContentArr.count {
                        self.filterV!.fContentArr[i].isUserShow = true
                }
                self.bannerSHowFilter()
            } else {
                KSToast("未配置")
            }
            
            
        }
        
        
        collectionView.dataSource = self
        collectionView.delegate = self
        collectionView.backgroundColor = .clear
        bg.addSubview(collectionView)
        collectionView.snp.makeConstraints { make in
            make.top.left.bottom.equalToSuperview()
            make.right.equalTo(saiBtn.snp.left)
        }
        
        
        
        saiBtn.snp.makeConstraints { make in
            make.right.equalToSuperview()
            make.width.equalTo(75)
            make.height.equalTo(comBannarItemH)
            make.centerY.equalToSuperview()
        }
    }
    //MARK: -- 显示筛选器
    func bannerSHowFilter() {
        self.filterV!.showFilterV()
    }
    func initWithFcontent(startY:CGFloat,templateFilter:[TemplateModel],rootTemp:MainTempModel? = nil) {
         
     
            
        self.filterV = KSDropDownFilterV(startY: startY,appearance: nil)
          if let rt = rootTemp {
            self.filterV?.rootTemp = rt

        }
        self.filterV?.assignTemplateFilterAndConfigFcontentArr(templateFilter)
        
        self.setBannerDefaultV()
       
        self.filterV?.closeClosure = {
            self.saiBtn.setTitleColor(.black, for: .normal)
        }
        self.filterV?.resetClosure = {
            self.setBannerDefaultV()
        }
        
        
        
        self.filterV?.confirmClosure = { arr in
            
            for (keyx,valuex) in self.filterV!.filterDic {
                
                if let indexx = self.fiBannerShowData.getIndexFor({ bonex in
                    bonex.param == keyx
                }) {
                    self.fiBannerShowData[indexx].content = valuex
                }
            }
            
            self.setBannerData(arr: self.fiBannerShowData)
            
            self.filterV!.close()
            if let clo = self.bannerComfirmClo {
                clo()
            }
            
            
            
        }
    }
    //MARK:  初始化和重置的时候使用
    func setBannerDefaultV() {
        self.filterV?.setFilterDefaultV()
        
        self.fiBannerShowData.removeAll()
        
        
        for item in self.filterV!.templateFilter {
            let pre = item.field_nm.unwrap
            var suf = item.default_value.unwrap
            if item.isFormSHow == "1" {
                
                fiBannerShowData.append(BannerData(param:pre,title: item.field_annotation.unwrap, content: suf))
            }
        }
        for (keyx,valuex) in self.filterV!.filterDic {
            
            if let indexx = self.fiBannerShowData.getIndexFor({ bonex in
                bonex.param == keyx
            }) {
                self.fiBannerShowData[indexx].content = valuex
            }
        }
        setBannerData(arr: fiBannerShowData)
    }
    
}

class ComSearColleCell: BadgeCollectionViewCell {
    lazy var bg:UIView = {
        let v = UIView()
        v.layer.cornerRadius = 15
        v.backgroundColor = UIColor(kshex: "#F0F4F9")
        v.isUserInteractionEnabled = false
        return v
    }()
    
    var title: UIButton = {
        let v  = UIButton()
        v.setTitleColor(UIColor(kshex:"#8991B0"), for: .normal)
        v.titleLabel?.font = UIFont.systemFont(ofSize: 12)
        v.titleLabel?.textAlignment = .center
        v.isUserInteractionEnabled = false
        return v
    }()
    var img:UIImageView = {
        var v = UIImageView()
        v.image = UIImage(named: "filter_down")
        return v
    }()
    
    convenience required init(coder : NSCoder){
        self.init()
    }
    
    func setHasContent(_ flag:Bool) {
        if flag {
            bg.layer.borderColor = UIColor(kshex: "#4972F9").cgColor
            bg.layer.borderWidth = 1
            title.setTitleColor(UIColor(kshex: "#4972F9"), for: .normal)
        } else {
            bg.layer.borderWidth = 0
            title.setTitleColor(UIColor(kshex: "#8991B0"), for: .normal)
            
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.initUtil()
    }
    
    func initUtil() {
        self.backgroundColor = .clear
        self.contentView.backgroundColor = .clear
        
        self.contentView.addSubview(bg)
        
        bg.snp.makeConstraints { make in
            make.edges.equalTo(UIEdgeInsets(top: 1, left: 1, bottom: 1, right: 1))
        }
        bg.addSubview(title)
        
        title.layer.cornerRadius = self.ks_height/2
        title.snp.makeConstraints { (make) in
            make.edges.equalTo(UIEdgeInsets(top: 0, left: 3, bottom: 0, right: 20))
        }
        bg.addSubview(img)
        img.snp.makeConstraints { make in
            make.centerY.equalToSuperview()
            make.right.equalToSuperview().offset(-8)
            make.width.equalTo(10)
            make.height.equalTo(6)
        }
        
        
    }
}
class FFButton: UIButton {
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.titleLabel?.textAlignment = .center
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    override func layoutSubviews() {
        super.layoutSubviews()
        self.titleLabel?.frame = CGRect(x: 3, y: 0, width: self.ks_width - 6 - 20, height: self.ks_height)
        self.imageView?.frame = CGRect(x: self.ks_width - 25, y: 8, width: 16, height: self.ks_height - 16)
        
    }
}
func inputTypeFilter(nm:String,param:String) -> TemplateModel {
    var t = TemplateModel(JSON:["":""])!
    t.isFormSHow = "1"
    t.isFilterShow = "1"
    t.field_nm = param
    t.field_annotation = nm
    t.field_type = TemplateType.input.rawValue
    return t
}
